package service

import (
	"api/app/ctl/models"
	"api/libs/errs"
	"gitee.com/dreamwood/ez"
	"time"
)

func CheckAlive() {
	crud := models.NewAppHostCrud()
	hosts, e := crud.FindBy(ez.M{"isOn": true}, nil, 0, 0)
	if errs.Try(e) {
		return
	}
	//收集沉默主机，并检查是否有其他负载在运行
	silentHosts := make([]*models.AppHost, 0)
	healthHosts := make([]*models.AppHost, 0)
	GetLock().Lock()
	defer GetLock().Unlock()
	for _, host := range hosts {
		if host.LastHeartBeatAt.Unix() < time.Now().Add(-11*time.Second).Unix() {
			//1分钟不心跳则认为已沉默
			silentHosts = append(silentHosts, host)
			//设置信息
			host.IsOn = false
			host.State = 0
			host.StateInfo = "心跳超时"
			e = crud.Factory.Update(host)
			errs.Try(e)
		} else {
			healthHosts = append(healthHosts, host)
		}
	}
	//检查沉默的主机中是否有其他负载还在工作
	for _, host := range silentHosts {
		find := false
		for _, healthHost := range healthHosts {
			if healthHost.AppId == host.AppId {
				find = true
			}
		}
		if find {
			continue
		}
		//处理下线的主机
		DealWithDeadHost(host)
	}
}

func DealWithDeadHost(host *models.AppHost) {
	//对于下线的主机，需要把相关的路由停用
	crud := models.NewAppRouteCrud()
	routes, e := crud.FindBy(ez.M{"appId": host.AppId}, nil, 0, 0)
	if errs.Try(e) {
		return
	}
	for _, route := range routes {
		//route.IsOn = false
		e = crud.Factory.Delete(route)
		errs.Try(e)
	}
	//并发出通知，通知管理员
	//todo
}
